<template>
  <Row>
    <Col span="6">
        <card class="card" icon="ios-options">
          <p slot="title" @click="FTreeClick" style="cursor: pointer">
            <Icon type="md-reorder"></Icon>
            {{firstdata.title}}
          </p>
          <a href="#" slot="extra" @click.prevent="edit(firstdata)">
            编辑
          </a>
          <CellGroup>
            <Tree :data="datalist" @on-select-change="clickTree"></Tree>
          </CellGroup>
        </card>
    </Col>
    <Col span="17" offset="1" v-show="this.state">
      <Modal :loading="btnLoading1" v-model="modalEdit1" title="网格基本信息" width="500" cancel-text="关闭"
             @on-ok="ok(paramData)" @on-cancel="modalEdit1=false" ok-text="确定">
        <Form :model="paramData">
          <Row class="item1">
            <Col span="5" style="text-align: right" class="">名称:</Col>
            <Col span="13" offset="1">
              <Input v-model="paramData.title"></Input>
            </Col>
          </Row>
          <Row class="item1" v-if="parseInt(this.current.level)<7">
            <Col span="5" style="text-align: right" class="">坐标:</Col>
            <Col span="9" offset="1">
              <Input v-model="paramData.mapjson" v-if="parseInt(this.current.level)!==5"></Input>
<!--              <Input type="textarea" v-model="paramData.mapjson" v-if="parseInt(this.current.level)===5"></Input>-->
<!--              <span v-if="parseInt(this.current.level)===5">{{paramData.mapjson}}</span>-->
            </Col>
            <Col span="5" offset="1">
              <Button @click="map()">选择</Button>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal :loading="btnLoading1" v-model="modalEdit2" title="商户基本信息" width="500" cancel-text="关闭"
             @on-ok="ok2(paramData)" @on-cancel="modalEdit2=false" ok-text="确定">
        <Form :model="paramData">
          <Row class="item1">
            <Col span="5" style="text-align: right" class="">名称:</Col>
            <Col span="13" offset="1">
              <Input v-model="paramData.title"></Input>
            </Col>
          </Row>
          <Row class="item1">
            <Col span="5" style="text-align: right" class="">类型:</Col>
            <Col span="12" offset="1">
              <Select v-model="paramData.type" style="width: 75%;">
                <Option v-if="parseInt(this.current.level)===3" value="7">广场</Option>
                <Option v-if="parseInt(this.current.level)===3" value="6">公园</Option>
                <Option v-if="parseInt(this.current.level)===4" value="5">单位</Option>
                <Option v-if="parseInt(this.current.level)===4" value="4">公司</Option>
                <Option v-if="parseInt(this.current.level)===5" value="3">商户</Option>
                <Option v-if="parseInt(this.current.level)===5" value="2">事业单位</Option>
                <Option v-if="parseInt(this.current.level)===5" value="1">银行</Option>
              </Select>
            </Col>
          </Row>
          <Row class="item1">
            <Col span="5" style="text-align: right" class="">坐标:</Col>
            <Col span="9" offset="1">
              <Input v-model="paramData.mapjson"></Input>
            </Col>
            <Col span="5" offset="1">
              <Button @click="map()">选择</Button>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal v-model="modalMap" fullscreen title="地图选点" @on-ok="okMap()">
        <div class="amap-page-container">
          <el-amap-search-box v-if="parseInt(this.current.level)<=4 && this.headState===0" class="search-box" :search-option="searchOption"
                              :on-search-result="onSearchResult"></el-amap-search-box>
          <el-amap vid="amap" class="amap-demo" :zoom="zoom" :center="center" :events="events">
            <el-amap-marker vid="index_center" :position="center"></el-amap-marker>
            <el-amap-polygon v-for="(polygon, index) in polygons" :key="index" :vid="polygon"
                             :path="polygon.path" :fillColor="polygon.fillColor" :bubble="polygon.bubble"
                             :fillOpacity="polygon.fillOpacity" :editable="polygon.editable"></el-amap-polygon>
          </el-amap>
        </div>
        <div class="toolbar">
          坐标: [{{ lng }}, {{ lat }}] <span v-if="this.address!=''">地址:</span> {{ address }}
        </div>
      </Modal>

      <Modal v-model="modalMap2" fullscreen title="小组区域选择" @on-cancel="cancelMap()" @on-ok="okMap()">
        <div class="amap-page-container">
<!--          <el-amap-search-box class="search-box" :search-option="searchOption"-->
<!--                              :on-search-result="onSearchResult"></el-amap-search-box>-->
          <el-amap vid="amap2" class="amap-demo" :zoom="zoom" :center="center">
<!--            <el-amap-polygon v-for="(polygon, index) in polygons" :key="index" :vid="polygon"-->
<!--                             :path="polygon.path" :fillColor="polygon.fillColor" :bubble="polygon.bubble"-->
<!--                             :fillOpacity="polygon.fillOpacity" :editable="polygon.editable"></el-amap-polygon>-->
          </el-amap>
        </div>
      </Modal>

      <div style="height:30px">
        <h3 style="float: left; font-weight: bold">当前节点：{{this.current.title}}</h3>
      </div>
      <Tabs :animated="false" :value="currentTab" @on-click="currentTabChanged">
        <TabPane label="下级" name="down">
          <div style="margin-bottom: 20px">
            <Col span="5">
              <Input style="width: 90%;" placeholder="名称" v-model="searchText"/>
            </Col>
            <Button type="info" @click="downlist">
              <Icon type="md-search"/>
              搜索
            </Button>
            <Button type="info" @click="create1" style="margin-left: 10px">
              <Icon type="md-add"/>
              添加
            </Button>
          </div>
          <Table border :loading="loading" :columns="columns1" :data="datalist2"></Table>
          <div class="page_style">
            <div style="float: right; margin-left: 50px; height: 32px; line-height: 32px">共 {{ totalnum }} 条</div>
            <Page style="text-align: right" :total="totalnum" :current="currentPageNo" :page-size="currentPageSize"
                  @on-change="change"/>
          </div>
        </TabPane>
        <TabPane :label="tabLabel" name="company" v-if="parseInt(this.current.level)<=5&&parseInt(this.current.level)>=3">
          <div style="margin-bottom: 20px">
            <Col span="5">
              <Input style="width: 90%;" placeholder="名称" v-model="searchText"/>
            </Col>
            <Button type="info" @click="company">
              <Icon type="md-search"/>
              搜索
            </Button>
            <Button type="info" @click="create2" style="margin-left: 10px">
              <Icon type="md-add"/>
              添加
            </Button>
          </div>
          <Table border :loading="loading" :columns="columns2" :data="datalist3"></Table>
          <div class="page_style">
            <div style="float: right; margin-left: 50px; height: 32px; line-height: 32px">共 {{ totalnum2 }} 条</div>
            <Page style="text-align: right" :total="totalnum2" :current="currentPageNo" :page-size="currentPageSize"
                  @on-change="change2"/>
          </div>
        </TabPane>
      </Tabs>
    </Col>
    <Col span="17" offset="1" v-show="!this.state">
      <div style="height:30px">
        <h3 style="float: left; font-weight: bold">当前节点：{{this.current.title}}</h3>
      </div>
      <Divider />
      <Form v-if="floordata.length === 0" :inline="true" :model="form" :label-width="40">
        <FormItem label="层数">
          <Input v-model="form.ceng"></Input>
        </FormItem>
        <FormItem label="户数">
          <Input v-model="form.hu"></Input>
        </FormItem>
        <Button class="ml10" @click="createCengHu">生成楼层</Button>
      </Form>
      <unit v-if="showFloor" :unit="unit" :fdata="floordata" :path="currentPath" @refresh="refresh" @save="save"></unit>
    </Col>
  </Row>
</template>

<script>
import {
  grid_maintain,
  grid_downlist_floor,
  grid_maintain_create_floor,
  grid_maintain_create_floor_ceng,
  grid_maintain_create,
  auditMailFloorService_delete,
  grid_downlist,
  auditmailcompany_create,
  auditmailcompany_list,
  auditMailFloorService_layerList
} from '@/api/eventlist'
import { transData } from '@/libs/tools'
import unit from './unit'

export default {
  components: {
    unit
  },
  data () {
    let self = this
    return {
      tabLabel: '基础设施', // tab名
      currentPath: '', // 临时路径
      showFloor: false, // 层户组件初始值（刷新用）
      optionState: 0, // 操作状态（创建还是编辑）
      mapState: 0, // map方法执行判断标记
      mapState_company: 0, // map针对商户判断标记
      headState: 1, // 用于对头节点编辑中地图搜索框显示
      polygonTemp: [], // 小组级别临时存储的多边形路径
      // 多边形
      polygons: [
        {
          bubble: true,
          editable: true,
          fillOpacity: '0.2',
          fillColor: '#f77777',
          path: []
        }
      ],
      selectVal: '', // 当前select选中数据
      currentTab: '', // 当前tab绑定数据
      // 单元以下级别模拟数据
      unit: '0', // 层户单元
      floordata: [], // 层户组件数据
      cfloordata: [], // 临时层户组件数据
      form: {
        ceng: 1,
        hu: 1
      },
      state: true, // 单元级别切换显示
      params: {
        pageNo: '',
        pageSize: ''
      },
      totalnum: 0, // 下级总数
      totalnum2: 0, // 下级总数
      currentPageNo: 1, // 当前页数
      currentPageSize: 8, // 当前页条数
      searchText: '', // 搜索节点内容
      center: [123.4650090000, 41.6772870000], // 默认沈阳坐标点
      markers: [[0, 0], [0, 0]],
      zoom: 9, // 缩放
      loading: false,
      btnLoading1: true, // 创建、编辑加载
      btnLoading2: true, // 删除加载
      title: '', // 网格名
      current: [], // 当前树节点信息
      modalEdit1: false, // 下级编辑模态框
      modalEdit2: false, // 商户编辑模态框
      modalMap: false, // 地图选点模态框
      modalMap2: false, // 地图选点模态框（小组专用）
      paramData: {}, // 模态框表单提交对象
      firstdata: {
        title: '沈阳市',
        mapjson: ''
      }, // 树的头节点
      datalist: [], // 树形结构
      datalist2: [], // 下级列表
      datalist3: [], // 商户列表
      searchOption: {
        city: '沈阳',
        citylimit: true
      },
      columns1: [
        { title: '序号', type: 'index', align: 'center' },
        { title: '名称', key: 'title', align: 'center' },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            let temp = []
            temp.push(
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.edit1(params.row)
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.remove(params.row)
                  }
                }
              }, '删除')
            )
            return h('div', temp)
          }
        }
      ],
      columns2: [
        { title: '序号', type: 'index', width: 70, align: 'center' },
        {
          title: '标记类型',
          key: 'type',
          width: 230,
          align: 'center',
          render: (h, params) => {
            let type = this.autoType(params.row.type)
            return h('span', type)
          }
        },
        { title: '名称', key: 'title', width: 230, align: 'center' },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            let temp = []
            temp.push(
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.edit2(params.row)
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.remove2(params.row)
                  }
                }
              }, '删除')
            )

            return h('div', temp)
          }
        }
      ],
      // 工具栏地址,经纬度
      address: '',
      lng: 0,
      lat: 0,
      mapstr: '',
      events: {
        click (e) {
          let { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          // 这里通过高德 SDK 完成。
          const geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
        }
      }
    }
  },
  methods: {
    init () {
      this.tree(arr => {
        this.current = arr[0]
        this.downlist()
        this.autoCompanyTab()
      })
    },
    // 树
    tree (thing) {
      grid_maintain().then(res => {
        if (res.data.errcode === 0) {
          const arr = transData(res.data.data, 'id', 'pid', 'children')
          this.datalist = arr[0].children
          this.firstdata = arr[0]
          if (thing !== undefined) thing(arr)
          // console.log('格式化后的树', arr)
        } else {
          this.$Notice.error({
            title: '获取树形结构失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 获取下级列表
    downlist () {
      const param = {
        pid: this.current.id,
        pageNo: this.currentPageNo,
        pageSize: this.currentPageSize
      }
      this.loading = true
      if (this.searchText !== '') param['title'] = this.searchText
      if (parseInt(this.current.level) >= 6) {
        grid_downlist_floor(param).then(res => {
          if (res.data.errcode === 0) {
            this.datalist2 = res.data.data.results
            this.totalnum = res.data.data.totalRecord
            this.loading = false
          } else {
            this.$Notice.error({
              title: '获取小组下级列表失败',
              desc: res.data.errmsg
            })
          }
        })
      } else {
        grid_downlist(param).then(res => {
          if (res.data.errcode === 0) {
            this.datalist2 = res.data.data.results
            this.totalnum = res.data.data.totalRecord
            this.loading = false
          } else {
            this.$Notice.error({
              title: '获取下级列表失败',
              desc: res.data.errmsg
            })
          }
        })
      }
    },
    // 公司列表
    company () {
      const param = {
        grid_id: this.current.id,
        pageNo: this.currentPageNo,
        pageSize: this.currentPageSize
      }
      this.loading = true
      if (this.searchText !== '') param['title'] = this.searchText
      auditmailcompany_list(param).then(res => {
        if (res.data.errcode === 0) {
          this.datalist3 = res.data.data.results
          // console.log('商户返回结果', this.datalist3)
          this.totalnum2 = res.data.data.totalRecord
          this.loading = false
        } else {
          this.$Notice.error({
            title: '获取公司列表失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // 当前树节点点击事件
    clickTree (data, res) {
      this.current = res
      this.currentPageNo = 1
      this.autoCompanyTab()
      this.mapState_company = 0
      // console.log('当前树节点', this.current)
      if (parseInt(this.current.level) === 102) {
        this.state = false
        this.form.ceng = 1
        this.form.hu = 1
        this.unit = this.current.title
        this.currentPath = this.current.path + this.current.id + '-'
        let pid = this.current.id
        this.showFloor = false
        auditMailFloorService_layerList({ pid: pid }).then(res => {
          if (res.data.errcode === 0) {
            this.floordata = res.data.data
            this.showFloor = true
          } else {
            this.$Notice.error({
              title: '获取层户列表失败',
              desc: res.data.errmsg
            })
          }
        })
      } else {
        this.state = true
      }
      if (this.current.id !== undefined) {
        this.company({ grid_id: this.current.id })
        this.downlist({ pid: this.current.id })
      }
      this.currentTab = 'down'
      // console.log(this.current.id)
    },
    // 树头节点点击事件
    FTreeClick () {
      this.current = this.firstdata
      this.currentPageNo = 1
      this.autoCompanyTab()
      this.mapState_company = 0
      // console.log('当前头节点', this.current)
      this.downlist({ pid: this.current.id })
      this.company({ grid_id: this.current.id })
      this.state = true
      this.currentTab = 'down'
      // console.log(this.currentTab)
    },
    // 下级列表分页改变事件
    change (pageNo) {
      this.currentPageNo = pageNo
      this.downlist()
    },
    // 商户列表分页改变事件
    change2 (pageNo) {
      this.currentPageNo = pageNo
      this.company()
    },
    // 下级模态框提交
    ok (param) {
      // console.log(this.paramData)
      // console.log(parseInt(this.current.level))
      if (parseInt(this.current.level) >= 6) {
        grid_maintain_create_floor(this.paramData).then(res => {
          if (res.data.errcode === 0) {
            this.tree()
            this.downlist({ pid: this.current.id })
            this.$Message.success('操作成功')
            this.paramData = {}
            this.modalEdit1 = false
          } else {
            this.modalEdit1 = false
            this.$Message.error('操作失败')
          }
        })
      } else {
        grid_maintain_create(this.paramData).then(res => {
          if (res.data.errcode === 0) {
            this.tree()
            this.downlist({ pid: this.current.id })
            this.$Message.success('操作成功')
            this.paramData = {}
            this.modalEdit1 = false
          } else {
            this.modalEdit1 = false
            this.$Message.error('操作失败')
          }
        })
        // this.FTreeClick()
      }
      this.tree()
      this.downlist({ pid: this.current.id })
    },
    // 商户模态框提交
    ok2 () {
      // console.log(this.paramData)
      auditmailcompany_create(this.paramData).then(res => {
        if (res.data.errcode === 0) {
          this.company({ grid_id: this.current.id })
          this.$Message.success('操作成功')
          this.paramData = {}
          this.modalEdit2 = false
        } else {
          this.modalEdit2 = false
          this.$Message.error('操作失败')
        }
      })
    },
    // 下级创建
    create1 () {
      this.headState = 1
      this.modalEdit1 = true
      this.polygons[0].path = []
      this.paramData = {}
      this.optionState = 0
      // console.log('-当前级别-', this.current.level)
      // 小组--6  楼--101  单元--102
      if (parseInt(this.current.level) >= 6) {
        this.paramData.pid = this.current.id
        this.paramData.path = this.current.path + this.current.id + '-'
        if (parseInt(this.current.level) === 6) {
          this.paramData.level = 101
          this.polygons[0].path = JSON.parse(this.current.mapjson)
          let path = JSON.parse(this.current.mapjson)
          let total_lng = 0.0
          let total_lat = 0.0
          path.forEach(arr => {
            total_lng += arr[0]
            total_lat += arr[1]
          })
          let newlng = total_lng / path.length
          let newlat = total_lat / path.length
          this.center = [newlng, newlat]
          this.mapState = 1
        } else if (parseInt(this.current.level) === 101) {
          this.paramData.level = 102
        }
      } else {
        this.paramData.pid = this.current.id
        this.paramData.level = parseInt(this.current.level) + 1
        this.paramData.path = this.current.path + this.current.id + '-'
        if (parseInt(this.current.level) === 5) {
          let current_center = this.current.mapjson
          // console.log('map', current_center)
          let str = current_center.split(',')
          this.center = []
          this.center.push(str[0])
          this.center.push(str[1])
          this.autoPolygon()
        }
      }
      this.autoZoom()
      // console.log('create:', this.current.id)
    },
    // 商户创建
    create2 () {
      this.headState = 1
      this.modalEdit2 = true
      this.polygons[0].path = []
      this.paramData = {}
      this.paramData.grid_id = this.current.id
      this.mapState = 0
      this.autoZoom()
    },
    // 登录账号编辑
    edit (item) {
      this.headState = 0
      this.modalEdit1 = true
      this.optionState = 1
      this.paramData = {}
      this.paramData.id = item.id
      this.paramData.title = item.title || ''
      this.paramData.mapjson = item.mapjson || ''
      this.current.level = 4
      if (item.mapjson !== undefined) {
        let current_center = item.mapjson
        let str = current_center.split(',')
        this.center = []
        this.center.push(str[0])
        this.center.push(str[1])
        this.lng = str[0]
        this.lat = str[1]
      }
      this.autoZoom()
    },
    // 下级编辑
    edit1 (item) {
      this.headState = 1
      this.modalEdit1 = true
      this.polygons[0].path = []
      this.optionState = 1
      this.paramData = {}
      this.paramData.id = item.id
      this.paramData.title = item.title || ''
      this.paramData.mapjson = item.mapjson || ''
      if (item.mapjson !== undefined) {
        if (parseInt(this.current.level) === 5) {
          this.polygons[0].path = JSON.parse(item.mapjson)
          this.polygonTemp = item.mapjson
          let current_center = this.polygons[0].path[0]
          this.center = []
          this.center = current_center
        } else {
          let current_center = item.mapjson
          let str = current_center.split(',')
          this.center = []
          this.center.push(str[0])
          this.center.push(str[1])
          this.lng = str[0]
          this.lat = str[1]
        }
      }
      this.mapState = 1
      this.autoZoom()
      // console.log('当前中心点', this.center)
    },
    // 商户编辑
    edit2 (item) {
      this.headState = 1
      this.modalEdit2 = true
      this.polygons[0].path = []
      this.paramData.id = item.id
      this.paramData.title = item.title || ''
      this.paramData.type = item.type || ''
      this.paramData.mapjson = item.mapjson || ''
      // console.log('商户编辑的mapjson：', item.mapjson)
      if (item.mapjson !== undefined) {
        // console.log(parseInt(this.current.level))
        if (parseInt(this.current.level) === 4 || parseInt(this.current.level) === 5) {
          let current_center = item.mapjson
          let str = current_center.split(',')
          this.center = []
          this.center.push(str[0])
          this.center.push(str[1])
          // console.log('商户编辑当前级别为5时候的中心点：', this.center)
          this.lng = str[0]
          this.lat = str[1]
        }
      }
      this.mapState = 1
      this.autoZoom()
    },
    // 删除节点
    remove (item) {
      this.$Modal.confirm({
        title: '确认删除此节点及其子节点么？',
        content: '<p>（此操作不可逆，请谨慎操作）</p >',
        loading: this.btnLoading2,
        onOk: () => {
          if (parseInt(this.current.level) >= 6) {
            grid_maintain_create_floor({ id: item.id, del_flag: '1' }).then(res => {
              if (res.data.errcode === 0) {
                this.$Modal.remove()
                this.downlist({ pid: this.current.id })
                this.tree()
                this.$Message.success('删除成功')
                this.paramData = {}
              } else {
                this.$Modal.remove()
                this.$Message.error('删除失败')
              }
            })
          } else {
            auditMailFloorService_delete({ id: item.id, del_flag: '1' }).then(res => {
              if (res.data.errcode === 0) {
                this.$Modal.remove()
                this.downlist({ pid: this.current.id })
                this.tree()
                this.$Message.success('删除成功')
              } else {
                this.$Modal.remove()
                this.$Message.error('删除失败')
              }
            })
          }
        },
        onCancel: () => {
          this.$Modal.remove()
          this.$Message.info('操作已取消')
        }
      })
    },
    // 删除商户
    remove2 (item) {
      this.$Modal.confirm({
        title: '确认删除此商户么？',
        content: '<p>（此操作不可逆，请谨慎操作）</p >',
        loading: this.btnLoading2,
        onOk: () => {
          auditmailcompany_create({ id: item.id, del_flag: '1' }).then(res => {
            if (res.data.errcode === 0) {
              this.$Modal.remove()
              this.company({ grid_id: this.current.id })
              this.$Message.success('删除成功')
            } else {
              this.$Modal.remove()
              this.$Message.error('删除失败')
            }
          })
        },
        onCancel: () => {
          this.$Modal.remove()
          this.$Message.info('操作已取消')
        }
      })
    },
    // 地图选点
    map () {
      if (parseInt(this.current.level) === 5 && this.mapState_company === 0) {
        this.modalMap2 = true
        this.mapState = 0
      } else {
        this.modalMap = true
        if (this.current.mapjson !== '' && this.current.mapjson !== undefined) {
          if (this.mapState !== 1) {
            // console.log('进入地图选点状态为0处理')
            let current_center = this.current.mapjson
            let str = current_center.split(',')
            this.center = []
            this.center.push(str[0])
            this.center.push(str[1])
            this.lng = str[0]
            this.lat = str[1]
          }
        }
      }
    },
    cancelMap () {
      if (this.optionState === 0) {
        this.autoPolygon()
      } else {
        this.polygons[0].path = JSON.parse(this.polygonTemp)
      }
    },
    okMap () {
      if (parseInt(this.current.level) === 5 && this.mapState !== 1 && this.mapState_company === 0) {
        let path = this.polygons[0].path
        let newpath = []
        for (let i = 0; i < path.length; i++) {
          let lng = path[i].lng
          let lat = path[i].lat
          let point = [lng, lat]
          newpath.push(point)
        }
        // console.log('当前多边形路径：', this.polygons[0].path)
        this.paramData.mapjson = JSON.stringify(newpath)
        // console.log('新的多边形路径：', this.paramData.mapjson)
      } else {
        this.paramData.mapjson = this.lng + ',' + this.lat
      }
      this.mapState = 0
    },
    // 根据当前中心点自动生成一组四边形坐标
    autoPolygon () {
      let lng = parseFloat(this.center[0])
      let lat = parseFloat(this.center[1])
      let center = [lng, lat]
      let lng1 = lng + 0.002
      let lat1 = lat
      let center1 = [lng1, lat1]
      let lng2 = lng + 0.002
      let lat2 = lat + 0.002
      let center2 = [lng2, lat2]
      let lng3 = lng
      let lat3 = lat + 0.002
      let center3 = [lng3, lat3]
      this.polygons[0].path = []
      this.polygons[0].path.push(center)
      this.polygons[0].path.push(center1)
      this.polygons[0].path.push(center2)
      this.polygons[0].path.push(center3)
    },
    // 地图搜索框
    onSearchResult (pois) {
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0 && pois.length === 1) {
        console.log(123)
        this.zoom = 14
        this.center = [pois[0].lng, pois[0].lat]
        this.lng = pois[0].lng
        this.lat = pois[0].lat
      } else {
        console.log(456)
        pois.forEach(poi => {
          let { lng, lat } = poi
          lngSum += lng
          latSum += lat
        })
        let mapcenter = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.zoom = 14
        this.center = [mapcenter.lng, mapcenter.lat]
        this.lng = mapcenter.lng
        this.lat = mapcenter.lat
      }
    },
    // 创建层户
    createCengHu () {
      this.floordata = []
      this.cfloordata = []
      for (let i = 0; i < this.form.ceng; i++) {
        let obj = {
          title: (i + 1) + 'F',
          list: []
        }
        for (let j = 0; j < this.form.hu; j++) {
          obj.list.push({
            title: this.unit + '-' + (i + 1) + '-' + (j + 1)
          })
        }
        this.cfloordata.push(obj)
      }
      // console.log('当前生成的层户', this.cfloordata)
      this.$Modal.confirm({
        title: '提示',
        content: '确认生成' + this.form.ceng + '层' + this.form.hu + '户的楼么？',
        loading: this.btnLoading2,
        onOk: () => {
          this.floordata = this.cfloordata
          this.currentPath = this.current.path + this.current.id + '-'
          this.save(this.floordata)
        },
        onCancel: () => {
        }
      })
    },
    // 保存数据的回调
    save (data) {
      this.paramData = {}
      this.paramData.pid = this.current.id
      this.paramData.path = this.current.path + this.current.id + '-'
      this.paramData.level = 103
      // const str = JSON.stringify(data)
      this.paramData.layerlist = data
      // this.showFloor = false
      this.currentPath = this.paramData.path
      // console.log('组件保存内容', this.paramData)
      grid_maintain_create_floor_ceng(this.paramData).then(res => {
        if (res.data.errcode === 0) {
          // this.showFloor = true
          this.$Modal.remove()
          this.$Message.success('保存成功')
          this.refresh()
          this.paramData = {}
        } else {
          this.$Message.error('保存失败')
        }
      })
    },
    // 层户组件刷新
    refresh () {
      // console.log('组件刷新')
      let pid = this.current.id
      this.showFloor = false
      auditMailFloorService_layerList({ pid: pid }).then(res => {
        if (res.data.errcode === 0) {
          this.floordata = res.data.data
          this.showFloor = true
          // console.log('进入刷新成功')
        } else {
          this.$Notice.error({
            title: '获取层户列表失败',
            desc: res.data.errmsg
          })
        }
      })
    },
    // Tab商户标签根据级别切换
    autoCompanyTab () {
      if (parseInt(this.current.level) === 3) {
        this.tabLabel = '基础设施'
      } else {
        this.tabLabel = '社会组织'
      }
    },
    // Tab标签选中
    currentTabChanged (name) {
      if (name === 'company') {
        this.autoCompanyTab()
        this.currentPageNo = 1
        // this.currentPageSize = 8
        this.company({ grid_id: this.current.id })
        this.mapState_company = 1
        this.currentTab = 'company'
        // console.log(this.currentTab)
      } else {
        this.currentPageNo = 1
        // this.currentPageSize = 8
        this.downlist()
        this.mapState_company = 0
        this.currentTab = 'down'
        // console.log(this.currentTab)
      }
    },
    // 根据级别调整zoom
    autoZoom () {
      if (parseInt(this.current.level) === 6) {
        this.zoom = 17 // 小组
      } else if (parseInt(this.current.level) === 5) {
        this.zoom = 16 // 小区
      } else if (parseInt(this.current.level) === 4) {
        this.zoom = 15 // 社区
      } else if (parseInt(this.current.level) === 3) {
        this.zoom = 13 // 街道
      } else if (parseInt(this.current.level) === 2) {
        this.zoom = 12 // 区
      }
    },
    // 商户表格标记类型转换
    autoType (value) {
      if (value === '1') {
        return '银行'
      } else if (value === '2') {
        return '事业单位'
      } else if (value === '3') {
        return '商户'
      } else if (value === '4') {
        return '公司'
      } else if (value === '5') {
        return '单位'
      } else if (value === '6') {
        return '公园'
      } else if (value === '7') {
        return '广场'
      }
    }
  },
  mounted () {
    this.init()
  }
}
</script>
<style lang='less'>
  // 表格滚动条
  .ivu-table-overflowX {
    overflow-x: hidden;
  }

  // 模态框
  .item1 {
    height: 42px;
    line-height: 40px;
  }

  // 地图
  .amap-page-container {
    position: relative;
    width: 100%;
    height: 88%;
  }

  // 地图选点预览工具栏
  .toolbar {
    display: block;
    text-align: center;
    height: 20px;
    margin-top: 50px;
  }

  // 地图搜索框
  .search-box {
    display: inline-block;
    position: absolute;
    top: 20px;
    left: 20px;
  }

  // 分页
  .page_style {
    margin-top: 10px;
    /*text-align: right;*/
    position: relative;
  }
</style>
